<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="../js/babel.js"></script>
</head>

<body>
  <div id="root"></div>
</body>

</html>

<script type="text/babel">
  class Life extends React.Component {
    state = {
      opacity: 1
    }

    death = () => {
      // 点击卸载组件
      ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    }

    // 组件挂载之后 触发
    componentDidMount() {
      this.timer = setInterval(() => {
        let { opacity } = this.state
        opacity -= 0.1
        if (opacity <= 0) {
          opacity = 1
        }
        this.setState({
          opacity
        })
      }, 200)
    }

    // 组件将要被卸载时 触发
    componentWillUnmount() {
      // 在组件将要被卸载之前 清除定时器 不然定时器依然存在
      clearInterval(this.timer)
    }

    render() {
      return (
        <div>
          <h2 style={{ opacity: this.state.opacity }}>React 学不会怎么办？</h2>
          <button onClick={this.death}>click me</button>
        </div>
      )
    }
  }

  ReactDOM.render(<Life />, document.getElementById('root'))

</script>